// CyTargetLinker RIN conversion,
//
// scripts to create RIN network files for several online databases
// can be used with the CyTargetLinker app for Cytoscape
//
// Copyright 2011-2013 Department of Bioinformatics - BiGCaT, Maastricht University
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

package cytargetlinker.conversion;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;

import cytargetlinker.conversion.ArgsParser.AFilesAttributes;
import cytargetlinker.conversion.ArgsParser.AFilesIn;
import cytargetlinker.conversion.ArgsParser.AFilesOut;
import cytargetlinker.conversion.ArgsParser.AHelp;
import cytargetlinker.conversion.ArgsParser.GraphBuilder;
import cytargetlinker.conversion.graph.Graph;

/**
 * WORK IN PROGRESS
 * 
 * connects to the ChEMBL SPARQL endpoint and extracts
 * all drug-target interactions and creates RIN file
 * 
 * @author martina
 *
 */
public class ChEMBLParser {

	private final static Logger log = Logger.getLogger(MiRecords.class.getName());
	private static Args pargs;
	private interface Args extends AHelp, AFilesIn, AFilesOut, AFilesAttributes {}
	
	/**
	 * USAGE: java -cp conversion.jar cytargetlinker.conversion.ChEMBLParser
	 * 
	 * REQUIRED ARGUMENTS:
	 * [-o] = output file path
	 * [-m] = list of bridgedb files for identifier mapping
	 * [-l] = log file path
	 * [--organism] = scientific name for the organism
	 *  
	 * OPTIONAL ARGUMENTS:
	 * [-n] = network name
	 * 
	 */
	public static void main(String argv[]) throws Exception {
		pargs = ArgsParser.parse(argv, Args.class);
		ChEMBLParser converter = new ChEMBLParser();
		converter.startConversion();
	}
	
	private Graph graph;
	
	public ChEMBLParser() {}
	
	private void startConversion() throws Exception {
		if(getLogFile() != null) {
			Utils.setUpLogger(log, getLogFile(), false);
			
			log.info("conversion of ChEMBL file started ...\n");
			
			ArgsParser.convertAndWrite(null, pargs, new GraphBuilder() {
				public Graph buildGraph(File in) throws Exception {
					return run();
				}
			});
			
			log.info("ChEMBL network file created.\n\n");
		} else {
			System.out.println("Please specify log file ([-l file]!");
		}
	}
	
	private Graph run() throws IOException {
		graph = new Graph();
		System.out.println("running");
		String prefix = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
					"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>" +
					"PREFIX owl: <http://www.w3.org/2002/07/owl#>" +
					"PREFIX dc: <http://purl.org/dc/elements/1.1/>" +
					"PREFIX foaf: <http://xmlns.com/foaf/0.1/>" +
					"PREFIX chembl: <http://rdf.farmbio.uu.se/chembl/onto/#>" +
					"PREFIX bo: <http://www.blueobelisk.org/chemistryblogs/>" + 
					"PREFIX bibo: <http://purl.org/ontology/bibo/>" +
					"PREFIX cito: <http://purl.org/spar/cito/>" +
					"PREFIX cheminf: <http://semanticscience.org/resource/>" +
					"PREFIX pro: <http://purl.obolibrary.org/obo/>" +
					"PREFIX skos: <http://www.w3.org/2004/02/skos/core#>";	

		String sparqlQueryString = "SELECT ?prot ?uniprot ?mol ?smiles " +
				"WHERE { " + 
				"?prot rdfs:subClassOf <http://purl.obolibrary.org/obo#PR_000000001> ; " +
				"owl:sameAs ?uniprot . " + 
				"FILTER(STRSTARTS(STR(?uniprot), \"http://bio2rdf.org/uniprot:\")) " +
				"?assay chembl:hasTarget ?prot . " + 
				"?act chembl:onAssay ?assay ; " + 
				"chembl:forMolecule ?mol . " + 
				"?mol bo:smiles ?smiles . " + 
				"}";

		Query query = QueryFactory.create(prefix + sparqlQueryString);
		QueryExecution queryExecution = QueryExecutionFactory.sparqlService("http://rdf.farmbio.uu.se/chembl/sparql", query);
		ResultSet resultSet = queryExecution.execSelect();
		
		File file = new File("/home/martina/test.txt");
		BufferedWriter writer = new BufferedWriter(new FileWriter(file));
		
		
		List<String> proteins = new ArrayList<String>();
		List<String> drugs = new ArrayList<String>();
		int count = 0;
		while (resultSet.hasNext()) {
			QuerySolution solution = resultSet.next();
			String p = solution.get("prot").toString();
			p = p.replace("http://linkedchemistry.info/chembl/target/", "");
			String uniprot = solution.get("uniprot").toString();
			uniprot = uniprot.replace("http://bio2rdf.org/uniprot:", "");
			
			String mol = solution.get("mol").toString();
			mol = mol.replace("http://linkedchemistry.info/chembl/molecule/", "");
			String smiles = solution.get("smiles").toString();
			
			writer.write(uniprot + " (" + p + ")\t" + smiles + "  (" + mol + ")\n");
			
			if(!proteins.contains(uniprot)) {
				proteins.add(uniprot);
			}
			if(!drugs.contains(smiles)) {
				drugs.add(smiles);
			}
			count++;
		}
		
		System.out.println(proteins.size() + "\t" + drugs.size() + "\t" + count);
		return graph;
	}
	
	private File getLogFile() {
		if(pargs.isLogFile()) {
			return pargs.getLogFile();
		} else {
			if(pargs.isInput()) {
				return new File(pargs.getInput() + ".log");
			} else {
				return null;
			}
		}
	}
}
